<template>
  <div class="menuAll">
    <el-menu :default-active="activeIndex" :class="'el-menu-demo menuTopTitle ' + upMenu()" :style="menuStyle()" mode="horizontal" @select="PageSwitching" :background-color="menuColor()" :text-color="menuTextColor()" :active-text-color="menuActiveTextColor()">
      <div class="menuLogo">
        <!-- -------------------------------huacon----------------------------- -->
        <el-image :src="require('@/assets/img/u33.png')" style="width: 32px;height:35px;" fit="fill" v-if="Oem_name==='huacon'"></el-image>
        <div class="menuLogoTitle" v-if="Oem_name==='huacon'">{{$t('title.力控华康工业防火墙')}}</div>
        <!-- -------------------------------andi----------------------------- -->
        <el-image :src="require('@/assets/img/andisec-home.png')" fit="fill" v-if="Oem_name==='andi'"></el-image>
        <!-- -------------------------------anheng----------------------------- -->
        <el-image :src="require('@/assets/img/anheng_white_logo.png')" style="width: 80px;padding:5px;" fit="fill" v-if="Oem_name==='anheng'"></el-image>
        <div class="menuLogoTitleAnheng" v-if="Oem_name==='anheng'">{{$t('安恒工业防火墙')}}</div>
        <!-- -------------------------------helishi----------------------------- -->
        <el-image :src="require('@/assets/img/helishi-logo.png')" style="width: 56px;height: 56px;padding:10px;" fit="fill" v-if="Oem_name==='helishi'"></el-image>
        <div class="menuLogoTitleAnheng" v-if="Oem_name==='helishi'">{{ $t('工业防火墙') }}</div>
        <!-- -------------------------------bozhi----------------------------- -->
        <el-image :src="require('@/assets/img/ELEX-ICFW.png')" style="width: 35px;height:32px;" fit="fill" v-if="Oem_name==='bozhi'"></el-image>
        <div align='center' class="menuLogoTitleBozhi" v-if="Oem_name==='bozhi'">{{$t('工控防火墙')}}</div>
        <!-- -------------------------------huanyu----------------------------- -->
        <el-image :src="require('@/assets/img/huanyuW.png')" v-if="Oem_name==='huanyu'" style="width: 126px;height: 56px;padding: 3px;" fit="fill"></el-image>
        <!-- -------------------------------jiepu----------------------------- -->
        <div class="menuLogoTitle" v-if="Oem_name==='jiepu'">{{ $t('工业防火墙') }}</div>
        <!-- -------------------------------lvmeng----------------------------- -->
        <div style="width:200px;padding-left:24px;" v-if="Oem_name==='lvmeng'">
          <el-image :src="require('@/assets/img/lvmeng_logo_in.png')" style="width: 44px;height: 26px;" fit="fill"></el-image>
        </div>
        <!-- -------------------------------yinke----------------------------- -->
        <el-image :src="require('@/assets/img/yinkeLogo.png')" style="padding-left:20px;padding-top:5px;width:175px;height:48px;line-height:60px;" fit="fill" v-if="Oem_name==='yinke'"></el-image>
        <!-- -------------------------------tiandun----------------------------- -->
        <el-image :src="require('@/assets/img/tiandun-logo.png')" style="width: 45px;height:45px;margin-right: 3px;margin-bottom: 5px;" fit="fill" v-if="Oem_name==='tiandun'"></el-image>
        <div align='center' class="menuLogoTitleAnheng" v-if="Oem_name==='tiandun'">{{$t('网安天盾工业防火墙')}}</div>
        <!-- -------------------------------wangan----------------------------- -->
        <el-image :src="require('@/assets/img/wangan-logo.png')" style="width: 75px;height:55px;margin-right: 3px;margin-bottom: 5px;" fit="fill" v-if="Oem_name==='wangan'"></el-image>
        <div align='center' class="menuLogoTitleAnheng" v-if="Oem_name==='wangan'">{{$t('工业防火墙')}}</div>
        <!-- -------------------------------wangteng----------------------------- -->
        <el-image :src="require('@/assets/img/wangteng-logo.png')" style="width: 220px;height:60px;padding:10px;" fit="fill" v-if="Oem_name==='wangteng'"></el-image>
        <!-- -------------------------------zhuoyue----------------------------- -->
        <div class="menuLogoTitle" v-if="Oem_name==='zhuoyue'">{{ $t('工业防火墙') }}</div>
        <!-- -------------------------------null----------------------------- -->
        <div class="menuLogoTitle" v-if="Oem_name==='null'">{{ $t('工业防火墙') }}</div>
      </div>
      <template>
        <el-menu-item v-for="(item, key) in menuShow" :index="item.href" :key="key">{{$t(item.name)}}</el-menu-item>
        <el-submenu class="MenuSubmenu" index='MenuSubmenu' v-if="numWidth < menu.length">
          <template slot="title">...</template>
          <el-menu-item v-for="(item, key) in menuHide" :index="item.href" :key="key">{{$t(item.name)}}</el-menu-item>
        </el-submenu>
      </template>
      <!-- <div class="menuLogout">
        <span style="color:#fff;">{{ userInfo.role }}</span>
        <el-link :underline="false" @click="testClick" style="color: #fff;width:50px;">{{$t('测试')}}</el-link>
        <el-link :underline="false" @click="logout" style="color: #fff;width:50px;margin-left:10px;">{{$t('退出')}}</el-link>
      </div> -->
      <div class="menuLogout" :style="lang==='zh' ?'width:230px':'width:280px'">
        <el-link :underline="false" :style="lang==='zh' ?'width:70px':'width:130px'" v-if="userInfo.roleID !== 2" @click="saveConfig" :class="saveConfigStyle()" type="success">{{$t('保存配置')}}</el-link>
        <el-dropdown :class="'menuSet ' + menuSet()" trigger="click" @command="handleCommand">
          <span class="el-dropdown-link">
            {{ $t('您好') + userInfo.username }}<i class="el-icon-arrow-down el-icon--right"></i>
          </span>
          <el-dropdown-menu slot="dropdown" style="width:180px;">
            <div style="margin:0 20px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:#606266;font-size:14px;" v-if="userInfo && userInfo.role">
              {{ $t(userInfo.role) }}
            </div>
            <el-dropdown-item icon="" :divided='(userInfo && userInfo.role)?true:false' command="set">
              <i class="el-icon-setting"></i> {{$t('首页配置')}}
            </el-dropdown-item>
            <el-dropdown-item>
              <svg-icon icon-class="language" style="margin-right:5px;" /> {{$t('语言')}}
              <el-dropdown-item icon="" command="zh">
                {{$t('中文切换')}}
              </el-dropdown-item>
              <el-dropdown-item icon="" command="en">
                {{$t('英文切换')}}
              </el-dropdown-item>
            </el-dropdown-item>
            <el-dropdown-item icon="" command="logout">
              <i class="el-icon-switch-button"></i> {{$t('退出')}}
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </el-menu>
    <template v-for="(item, key) in menu">
      <div v-if="item.child.length !== 0" :key="key">
        <left-menu v-if="activeIndex === item.href" v-bind:itemChild="item.child" />
      </div>
    </template>
    <Set ref="refSetDialogVisible" v-if="dialogVisible"></Set>
    <upload-file-chunk v-if="uploadFileChunkVisible" ref="refUploadFileChunkVisible"></upload-file-chunk>
    <upload-file-system-chunk v-if="uploadFileSystemChunkVisible" ref="refUploadFileSystemChunkVisible"></upload-file-system-chunk>
  </div>
</template>

<script>
import LeftMenu from './LeftMenu'
// import { stopWebMessage } from '@/api/connectivity'
import { EventSourcePolyfill } from 'event-source-polyfill'
import { exportSearchInfo } from '@/api/test'
import { saveSet, switchLanguage, getLanguageInfo } from '@/api/home'
import { getUserInfo, setRoleList, getSessionId, getOem } from '@/utils/auth'
import { mapGetters } from 'vuex'
import { logout } from '@/api/login'
import Set from './Set'
import Cookies from 'js-cookie'
import global from '@/global'
import Middle from '@/utils/middle.js'
import uploadFileChunk from './uploadFile/uploadFileChunk'
import uploadFileSystemChunk from './uploadFile/uploadFileSystemChunk'

export default {
  name: 'Menu',
  components: {
    LeftMenu,
    Set,
    uploadFileChunk,
    uploadFileSystemChunk
  },
  computed: {
    ...mapGetters([
      'permission_routes'
    ])
  },
  data () {
    return {
      dialogVisible: false,
      uploadFileChunkVisible: false,
      uploadFileSystemChunkVisible: false,
      activeIndex: '/menu',
      menu: [],
      menuShow: [],
      menuHide: [],
      userInfo: getUserInfo(),
      numWidth: 6,
      timer: null,
      source: null,
      faultText: '',
      notifyInstance: null,
      session_id: getSessionId(),
      Oem_name: getOem(),
      global: global,
      alert_id: null,
      alert_id_name: 'alert_id' + (window.location.href.split('/')[2].split(':')[1] || '443'),
      wanganStylelist: ['tiandun', 'wangan'],
      blueStyleList: ['lvmeng', 'yinke'],
      icoList: ['huacon', 'anheng', 'helishi', 'lvmeng', 'tiandun', 'wangan', 'wangteng', 'bozhi'],
      lang: this.$i18n.locale
    }
  },
  watch: {
    '$route.path': {
      handler (newVal) {
        let path_array = newVal.split('/')
        this.activeIndex = '/' + path_array[1]
      },
      immediate: true
    },
    numWidth (newVal) {
      if (newVal <= this.menu.length) {
        this.menuShow = []
        this.menuHide = []
        this.menu.forEach((item, index) => {
          if (index < newVal) {
            this.menuShow.push(item)
          } else {
            this.menuHide.push(item)
          }
        })
      } else {
        this.menuShow = []
        this.menuHide = []
        this.menu.forEach((item, index) => {
          this.menuShow.push(item)
        })
      }
    }
  },
  created () {
    let _that = this
    // window.isCloseHint = true
    window.addEventListener('beforeunload', function (e) {
      // if (window.isCloseHint) {
      //   var confirmationMessage = '要记得保存！你确定要离开我吗？';
      //   (e || window.event).returnValue = confirmationMessage // 兼容 Gecko + IE
      //   return confirmationMessage // 兼容 Gecko + Webkit, Safari, Chrome
      // }
      _that.$axios.post('/connectivity/stop_web_message', _that.$qs.stringify({
        alert_id: Cookies.get(_that.alert_id_name)
      }))
      _that.source.close()
    }, true)
    this.menuWidth()
    this.sourceWebMessage()
  },
  mounted () {
    const _that = this
    if (this.icoList.includes(this.Oem_name)) {
      var link = document.querySelector("link[rel*='icon']") || document.createElement('link')
      link.type = 'image/x-icon'
      link.rel = 'shortcut icon'
      link.href = 'static/ico/' + (this.icoList.includes(this.Oem_name) ? this.Oem_name : 'favicon') + '.ico'
      document.getElementsByTagName('head')[0].appendChild(link)
    }
    window.onresize = () => {
      return (() => {
        _that.numWidth = Number(((document.body.clientWidth - 462) / 96).toFixed(0))
      })()
    }
    Middle.$on('logout', () => {
      _that.logout()
    })
    Middle.$on('uploadFile', () => {
      _that.uploadFile()
    })
    Middle.$on('uploadSysFile', () => {
      _that.uploadSysFile()
    })
    this.$nextTick(() => {
      this.createdAsync()
    })
  },
  beforeDestroy () {
    this.source.close()
    let _that = this
    if (this.notifyInstance) {
      this.notifyInstance.close()
    }
    this.$axios.post('/connectivity/stop_web_message', this.$qs.stringify({
      alert_id: Cookies.get(_that.alert_id_name)
    }))
  },
  methods: {
    sourceWebMessage () {
      let _that = this
      _that.$axios.get('/connectivity/bind_message', {
        headers: { session_id: _that.session_id }
      })
      _that.source = new EventSourcePolyfill(global.BASE_URL + '/connectivity/web_message', {
        headers: { session_id: _that.session_id },
        heartbeatTimeout: 210000
      })
      _that.source.addEventListener('message', function (e) {
        var ndata = JSON.parse(e.data)
        if (ndata.type === 1) {
          if (_that.faultText !== ndata.data) {
            if (_that.notifyInstance) {
              _that.notifyInstance.close()
            }
            _that.faultText = ndata.data
            _that.notifyInstance = _that.$notify.warning({
              title: _that.$t('信息'),
              message: ndata.data,
              position: 'bottom-right',
              offset: 0,
              duration: 0,
              onClose: _that.faultClose
            })
          }
        } else if (ndata.type === 0) {
          if (ndata.alert_id) {
            Cookies.set(_that.alert_id_name, ndata.alert_id)
          }
        }
        // else if (ndata.type === 4) {
        //   setTimeout(() => {
        //     _that.source.close()
        //     _that.sourceWebMessage()
        //   }, 1000)
        // }
      })
      _that.source.addEventListener('open', function (e) {
        // console.log('open successfully')
      })
      _that.source.addEventListener('error', function () {
        // 类似的返回信息验证，这里是实例
        // console.log(err)

        _that.$axios.post('/connectivity/stop_web_message', _that.$qs.stringify({
          alert_id: Cookies.get(_that.alert_id_name)
        }))
        // if (err && err.error && err.error.message.indexOf('Reconnecting') !== -1) {
        //   setTimeout(() => {
        //     _that.source.close()
        //   }, 1000)
        // }
        // else {
        //   _that.source.close()
        // }
      })
    },
    faultClose (val) {
      this.faultText = ''
    },
    createdAsync () {
      if (this.$store.state.user.isSetRoutes) {
        this.menu = this.$store.state.user.roleInfo
        this.menuShow = []
        this.menuHide = []
        this.menu.forEach((item, index) => {
          if (index < this.numWidth) {
            this.menuShow.push(item)
          } else {
            this.menuHide.push(item)
          }
        })
        getLanguageInfo().then(res => {
          if (res.info === 'zh_CN') {
            this.$i18n.locale = 'zh'
            Cookies.set('language', 'zh')
          } else if (res.info === 'en_US') {
            this.$i18n.locale = 'en'
            Cookies.set('language', 'en')
          }
        })
      } else {
        this.$store.dispatch('user/logout')
      }
    },
    PageSwitching (val) {
      if (this.activeIndex !== val) {
        // this.activeIndex = val
        if (val !== '/menu') {
          this.permission_routes.forEach(item => {
            if (item.path === val) {
              this.$router.push(item.children[0].path)
            }
          })
        } else {
          this.$router.push(val)
        }
      }
    },
    logout () {
      if (this.notifyInstance) {
        this.notifyInstance.close()
      }
      this.source.close()
      logout().then(res => {
        this.$store.dispatch('user/logout').then(res => {
          // this.$router.push(`/login?redirect=${this.$route.fullPath}`)
          this.$router.push(`/login`)
          // this.$axios.post('/connectivity/stop_web_message', this.$qs.stringify({
          //   alert_id: Cookies.get('alert_id')
          // }))
          // }
          // })
        })
      })
    },
    testClick () {
      exportSearchInfo().then(res => {
        if (res[0]) {
          let blob = new Blob([res[0]], { type: 'text/csv,charset=UTF-8' })
          let objectUrl = URL.createObjectURL(blob)
          let link = document.createElement('a')
          link.download = res[1] // 文件名字
          link.href = objectUrl
          // 触发下载
          link.click()
          // window.location.href = objectUrl
        }
      })
    },
    handleCommand (data) {
      switch (data) {
        case 'logout':
          this.$confirm(this.$t('您是否要退出登录？'), this.$t('提示'), {
            closeOnClickModal: false,
            confirmButtonText: this.$t('确定'),
            cancelButtonText: this.$t('取消'),
            confirmButtonClass: 'confirmButton',
            cancelButtonClass: 'confirmCancelButton',
            type: 'warning'
          }).then(() => {
            this.logout()
          })

          break
        case 'set':
          this.dialogVisible = true
          this.$nextTick(() => {
            this.$refs.refSetDialogVisible.init()
          })
          break
        case 'zh':
          switchLanguage({language: 'zh_CN'}).then(res => {
            Cookies.set('language', data)
            this.$i18n.locale = data
            window.location.reload()
          })
          break
        case 'en':
          switchLanguage({language: 'en_US'}).then(res => {
            Cookies.set('language', data)
            this.$i18n.locale = data
            window.location.reload()
          })
          break
      }
    },
    saveConfig () {
      saveSet().then(res => {
        if (res.status === 0) {
          this.$message({
            message: this.$t('保存配置成功'),
            type: 'success'
          })
        }
      })
    },
    saveConfigStyle () {
      if (this.blueStyleList.includes(this.Oem_name)) {
        return 'lvmengSaveConfig'
      } else {
        return 'saveConfig'
      }
    },
    menuSet () {
      if (this.blueStyleList.includes(this.Oem_name)) {
        return 'menuLvmengSet'
      } else {
        return ''
      }
    },
    menuColor () {
      // 1D3250 393D49
      if (this.wanganStylelist.includes(this.Oem_name)) {
        return '#1D3250'
      } else if (this.blueStyleList.includes(this.Oem_name)) {
        return '#387ed3'
      } else if (this.Oem_name === 'huanyu') {
        return 'rgba(255, 255, 255, 0)'
      } else {
        return '#393D49'
      }
    },
    menuStyle () {
      if (this.Oem_name === 'huanyu') {
        return { backgroundImage: 'url(' + require(`../assets/img/huanyuMenuTop.png`) + ')', backgroundPosition: 'center', backgroundRepeat: 'no-repeat', backgroundSize: 'cover' }
      }
    },
    menuTextColor () {
      if (this.wanganStylelist.includes(this.Oem_name)) {
        return '#CCCCCC'
      } else if (this.blueStyleList.includes(this.Oem_name)) {
        return '#000'
      } else if (this.Oem_name === 'huanyu') {
        return '#fff'
      } else {
        return '#fff'
      }
    },
    menuActiveTextColor () {
      if (this.wanganStylelist.includes(this.Oem_name)) {
        return '#fff'
      } else if (this.blueStyleList.includes(this.Oem_name)) {
        return '#fff'
      } else if (this.Oem_name === 'huanyu') {
        return '#fff'
      } else {
        return '#009966'
      }
    },
    upMenu () {
      if (this.wanganStylelist.includes(this.Oem_name)) {
        return 'tiandunMenu'
      } else if (this.blueStyleList.includes(this.Oem_name)) {
        return 'lvmengMenu'
      } else if (this.Oem_name === 'huanyu') {
        return 'huanyuMenu'
      } else {
        return ''
      }
    },
    uploadFile () {
      this.uploadFileChunkVisible = true
      this.$nextTick(() => {
        this.$refs.refUploadFileChunkVisible.init()
      })
    },
    uploadSysFile () {
      this.uploadFileSystemChunkVisible = true
      this.$nextTick(() => {
        this.$refs.refUploadFileSystemChunkVisible.init()
      })
    },
    menuWidth () {
      if (this.lang === 'zh') {
        this.numWidth = Number(((document.body.clientWidth - 462) / 96).toFixed(0))
      } else {
        let wid = document.body.clientWidth - 462
        // 适配英文导航菜单，在页面不够宽时隐藏部分菜单
        if (wid < 108) {
          this.numWidth = 0
        } else if (wid < 252) {
          this.numWidth = 1
        } else if (wid < 429) {
          this.numWidth = 2
        } else if (wid < 561) {
          this.numWidth = 3
        } else if (wid < 734) {
          this.numWidth = 4
        } else if (wid < 870) {
          this.numWidth = 5
        } else {
          this.numWidth = 6
        }
      }
    }
  }
}
</script>
<style lang="less">
.MenuSubmenu {
  .el-submenu__title {
    font-size: 30px;
    height: 60px !important;
    padding: 0 !important;
    border: 0 !important;
  }
  .el-submenu__title:hover {
    background-color: #fff;
  }
  .el-submenu__icon-arrow {
    display: none;
  }
}
.menuTopTitle {
  display: flex;
  height: 60px;
  overflow: hidden;
}
.tiandunMenu {
  .el-menu-item.is-active {
    border-bottom: 5px solid #009966 !important;
  }
  .el-menu-item:hover {
    color: #fff !important;
  }
}
.lvmengMenu {
  .el-menu-item.is-active {
    border-bottom: 5px solid #009966 !important;
  }
  .el-menu-item:hover {
    background-color: rgba(255, 255, 255, 0.1) !important;
    color: #fff !important;
  }
}
.huanyuMenu {
  .el-menu-item {
    border-bottom: 0px solid #fff !important;
  }
  .el-menu-item.is-active {
    border-bottom: 0px solid #fff !important;
    background-color: rgba(0, 0, 0, 0.2) !important;
  }
  .el-menu-item:hover {
    background-color: rgba(0, 0, 0, 0.2) !important;
    color: #fff !important;
  }
}
</style>
<style scoped>
.aside {
  background-color: #393d49;
  /* padding: 0; */
}
.el-menu {
  border-bottom: none;
}
.menuLogout {
  height: 60px;
  margin-left: auto;
  flex-shrink: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}
.menuSet {
  color: #fff;
  margin: 0 10px;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
  overflow: hidden;
  word-break: break-all;
}
.menuLvmengSet {
  color: #000;
}
.menuLvmengSet:hover {
  color: #fff;
}
.menuLogo {
  float: left;
  flex-shrink: 0;
  width: 200px;
  height: 60px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}
.menuLogoTitle {
  margin-left: 7px;
  font-size: 16px;
  font-weight: 600;
  color: #009966;
  /* letter-spacing: 3px; */
}
.menuLogoTitleBozhi {
  margin-left: 7px;
  color: #fff;
  font-size: 18px;
  letter-spacing: 1px;
}
.menuLogoTitleAnheng {
  color: white;
  font-size: 16px;
}
.el-dropdown-link {
  cursor: pointer;
}
.saveConfig {
  color: #fff;
  margin-right: 10px;
}
.lvmengSaveConfig {
  color: #000;
  margin-right: 10px;
}
.lvmengSaveConfig:hover {
  color: #fff;
}
</style>
